package boundarys;

import java.awt.Label;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import ccrm.BoundryControl;
import controllers.MaintainingResidentialAreaController;
import controllers.ManageCategoriesController;
import entitys.Area;
import entitys.Category;
import entitys.Reply;
import enums.Command;
import enums.Result;

public class MaintainingResidentialAreaGUI extends AbstractGUI{

	/**
	 * Maintain residential area frame
	 */
	private JFrame frmCcrmmaintainResidetnitalArea;
	/**
	 * List of areas to store the result from server
	 */
	ArrayList<Area> arr=null;
	/**
	 * List of areas to add to the frame list
	 */
	private List AreasList;
	/**
	 * Labels
	 */
	private Label searchLabel;
	private Label AreaNameLabel;
	private Label areasindbLabel;
	/**
	 * Buttons
	 */
	private JButton ConfirmBtn;
	private JButton AddAreaBtn;
	private JButton RefreshBtn;
	private JButton ClearBtn;
	private JButton DeleteAreaBtn;
	/**
	 * area text field
	 */
	private JTextField textField;
	/**
	 * search text field
	 */
	private JTextField searchTextField;

	/**
	 * Constructor
	 */
	public MaintainingResidentialAreaGUI() {
		initialize();
		initGUI(frmCcrmmaintainResidetnitalArea);

	}

	/**
	 * 
	 * @return areas list
	 */
	public List getAreasList() {
		return AreasList;
	}

	/**
	 * sets areas list
	 * @param AreasList
	 */
	public void setAreasList(List AreasList) {
		this.AreasList = AreasList;
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmCcrmmaintainResidetnitalArea = new JFrame();
		/**
		 * Mouse Listener
		 * Whenever the frame is clicked it deselects the selected item in list
		 */
		frmCcrmmaintainResidetnitalArea.getContentPane().addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				AreasList.deselect(AreasList.getSelectedIndex());	
			}
		});
		frmCcrmmaintainResidetnitalArea.setTitle("CCRM>Maintain Residential Area");
		frmCcrmmaintainResidetnitalArea.setResizable(false);
		frmCcrmmaintainResidetnitalArea.setBounds(100, 100, 466, 426);
		frmCcrmmaintainResidetnitalArea.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
		frmCcrmmaintainResidetnitalArea.getContentPane().setLayout(null);
		
		AreasList = new List();
		/**
		 * Mouse Listener
		 * Whenever area is selected it sets the text field text to the area name
		 */
		AreasList.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				String tmp = (String)AreasList.getSelectedItem();
				textField.setText(tmp.substring(tmp.indexOf(" ")).trim());
			}
		});

		AreasList.setMultipleSelections(false);
		AreasList.setBounds(35, 75, 219, 221);
		frmCcrmmaintainResidetnitalArea.getContentPane().add(AreasList);
		
		/**
		 * sends the server a request to get areas list
		 */
		MaintainingResidentialAreaController.getAreas();
		
		areasindbLabel = new Label("Areas in db:");
		areasindbLabel.setBounds(35, 47, 203, 22);
		frmCcrmmaintainResidetnitalArea.getContentPane().add(areasindbLabel);
		
		AreaNameLabel = new Label("Area name:");
		AreaNameLabel.setBounds(9, 314, 90, 22);
		frmCcrmmaintainResidetnitalArea.getContentPane().add(AreaNameLabel);
		
		JButton RefreshBtn = new JButton("Refresh");
		/**
		 * Action Listener for Refresh Button
		 * Gets the updated areas list and shows it in the list
		 */
		RefreshBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(BoundryControl.GUIArr.size()==getIndex()+1)
				{
					MaintainingResidentialAreaController.getAreas();
				}
			}
		});
		RefreshBtn.setBounds(286, 183, 137, 43);
		frmCcrmmaintainResidetnitalArea.getContentPane().add(RefreshBtn);
		
		textField = new JTextField();
		textField.setBounds(101, 314, 153, 22);
		frmCcrmmaintainResidetnitalArea.getContentPane().add(textField);
		
		AddAreaBtn = new JButton("Add Area");
		/**
		 * Action Listener for Add Area Button
		 * if the area already exists or the name is empty it does not add 
		 * else adds new area to list and database
		 */
		AddAreaBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(BoundryControl.GUIArr.size()==getIndex()+1)
				{
					if(AreasList.getSelectedItem()!=null)
					{
						JOptionPane.showMessageDialog(frmCcrmmaintainResidetnitalArea, "Unable to add an existing area", "CCRM Maintian Residential Area", JOptionPane.ERROR_MESSAGE);
					}
					else if(textField.getText().equals(""))
					{
						JOptionPane.showMessageDialog(frmCcrmmaintainResidetnitalArea, "Please enter an area name", "CCRM Maintian Residential Area", JOptionPane.ERROR_MESSAGE);
					}
					else if(exists(AreasList, textField.getText()))
					{
						JOptionPane.showMessageDialog(frmCcrmmaintainResidetnitalArea, "Unable to add an existing area", "CCRM Maintian Residential Area", JOptionPane.ERROR_MESSAGE);
					}
					else
					{
						MaintainingResidentialAreaController.addArea(textField.getText(), getAreasList().getItemCount());//send request to add category
					}
				}
			}

		});
		AddAreaBtn.setBounds(286, 75, 137, 43);
		frmCcrmmaintainResidetnitalArea.getContentPane().add(AddAreaBtn);
		
		DeleteAreaBtn = new JButton("Delete Area");
		/**
		 * Action Listener for Delete Area Button
		 * if the area is not selected it shows corresponding message 
		 * else delete area name from list and updates the database
		 */
		DeleteAreaBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(BoundryControl.GUIArr.size()==getIndex()+1)
				{
					if(AreasList.getSelectedItem() == null)
						JOptionPane.showMessageDialog(frmCcrmmaintainResidetnitalArea, "Select a area to delete", "CCRM Maintain Residential Area", JOptionPane.ERROR_MESSAGE);
					else
					{
						String a = (String)AreasList.getSelectedItem();
						int aid = Integer.parseInt(a.substring(1,a.indexOf(" ")).trim());
						MaintainingResidentialAreaController.deleteArea((String)AreasList.getSelectedItem(), aid);
					}
				}
			}
		});
		DeleteAreaBtn.setBounds(286, 129, 137, 43);
		frmCcrmmaintainResidetnitalArea.getContentPane().add(DeleteAreaBtn);
	 	
		ClearBtn = new JButton("Clear");
		/**
		 * Action Listener for Clear Button
		 * Clears the type text field
		 */
		ClearBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(BoundryControl.GUIArr.size()==getIndex()+1)
				{
					textField.setText("");
				}
			}
		});
		ClearBtn.setBounds(270, 313, 89, 23);
		frmCcrmmaintainResidetnitalArea.getContentPane().add(ClearBtn);
		
		searchLabel = new Label("Search areas:");
		searchLabel.setBounds(35, 10, 106, 22);
		frmCcrmmaintainResidetnitalArea.getContentPane().add(searchLabel);
		
		searchTextField = new JTextField();
		/**
		 * Key Listener for search text field
		 * Whenever key is released it updates the area list by showing the names that contains the string that was typed
		 */

		searchTextField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if(searchTextField.getText().isEmpty())
					MaintainingResidentialAreaController.getAreas();
				else
					MaintainingResidentialAreaController.getAreas(searchTextField.getText());
			}
		});
		searchTextField.setColumns(10);
		searchTextField.setBounds(140, 10, 137, 22);
		frmCcrmmaintainResidetnitalArea.getContentPane().add(searchTextField);
		
		
		frmCcrmmaintainResidetnitalArea.setVisible(true);
	}
	
	/**
	 * 
	 * @param l
	 * @param text
	 * @return whether text exists in the list l
	 */
	public boolean exists(List l, String text) {
		for(int i=0;i<l.getItemCount();i++)
		{
			String tmp = (String)l.getItem(i);
			if(text.equals(tmp.substring(tmp.indexOf(" ")).trim()))
				return true;
		}
		return false;
	}
	
	/**
	 * Reply from server
	 * Does the right action according to the command that was sent from the controller
	 */
	@Override
	public void getReply(Object r) {
		// TODO Auto-generated method stub
		if(((Reply)r).command.equals(Command.GET_AREAS)) //if GET_AREAS reply is received
		{
			arr =(ArrayList<Area>) ((Reply)r).result;
			AreasList.removeAll();
			
			for(int i=0;i<arr.size();i++)
			{
				AreasList.add(arr.get(i).toString());
			}
		}
		
		else if(((Reply)r).command.equals(Command.GET_AREAS_WITH_PREFIX)) //if GET_AREAS reply is received
		{
			arr =(ArrayList<Area>) ((Reply)r).result;
			AreasList.removeAll();
			
			if(!arr.isEmpty())
			{
				for(int i=0;i<arr.size();i++)
				{
					AreasList.add(arr.get(i).toString());
				}
			}
		}
		
		else if(((Reply)r).command.equals(Command.ADD_AREA))
		{
			if (((Reply)r).result.equals(Result.OK))
			{
				System.out.println("Area added successfully!");
				JOptionPane.showMessageDialog(frmCcrmmaintainResidetnitalArea, "Area added successfully", "CCRM Maintain Residential Area", JOptionPane.INFORMATION_MESSAGE);
			}
			MaintainingResidentialAreaController.getAreas();
			
		}
		
		else if(((Reply)r).command.equals(Command.DELETE_AREA))
		{
			if (((Reply)r).result.equals(Result.OK))
			{
				System.out.println("Area deleted successfully!");
				JOptionPane.showMessageDialog(frmCcrmmaintainResidetnitalArea, "Area deleted successfully", "CCRM Maintain Residential Area", JOptionPane.INFORMATION_MESSAGE);
			}
			MaintainingResidentialAreaController.getAreas();			
		}
	}

}
